package com.wjh.web;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wjh.annotation.AccessLimit;
import com.wjh.base.ResponseApiCode;
import com.wjh.base.ResponseApiData;
import com.wjh.common.BaseInfo;
import com.wjh.common.LockConstant;
import com.wjh.order.entity.OrderEntity;
import com.wjh.order.request.QueryOrderPageRequest;
import com.wjh.order.request.SaveOrderRequest;
import com.wjh.service.IOrderService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

/**
 * 订单 AIP接口
 * 
 * @author wenjianhai
 * @date 2023/6/22
 * @since JDK 17
 */
@Tag(name = "订单 AIP接口", description = "订单 AIP接口")
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController extends BaseController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RedissonClient redissonClient;

    @Operation(summary = "商品下单", description = "商品下单")
    @AccessLimit(maxCount = 3, second = 60) // 限流 : 60秒钟内最多允许调用3次
    @PostMapping("/save")
    public ResponseApiData<?> save(@Validated @RequestBody SaveOrderRequest request) {
        log.info("商品下单-开始.请求参数:{}", JSON.toJSONString(request));

        if (request.getGoodsList().size() > 30) {
            return ResponseApiData.parameterFail("商品种类不能超过30");
        }
        // 当前登录人
        BaseInfo baseInfo = this.getBaseInfo();
        // 分布式锁
        RLock lock = null;

		try {
            String rdsKey = String.format(LockConstant.SAVE_ORDER_LOCK_NAME, baseInfo.getUserGuid());
			// 分布式锁
			lock = redissonClient.getLock(rdsKey);

			if (!lock.tryLock(LockConstant.SAVE_ORDER_LOCK_WAIT_TIME, LockConstant.SAVE_ORDER_LOCK_LEASE_TIME,
					TimeUnit.SECONDS)) {
                log.info("商品下单,获取锁失败.rdsKey:{}", rdsKey);
                if (lock.isLocked()) {
                    lock.unlock();
                }
                return ResponseApiData.fail(ResponseApiCode.REPEAT_OPT.getCode(), ResponseApiCode.REPEAT_OPT.getMessage());
			}
			orderService.save(request, baseInfo);
			return ResponseApiData.success();
		} catch (Exception e) {
			log.error(String.format("商品下单-失败.请求参数:%s", JSON.toJSONString(request)), e);
			return ResponseApiData.systemFail(e.getMessage());
		} finally {
            if (lock != null && lock.isLocked()) {
				lock.unlock();
			}
		}
    }

    @Operation(summary = "分页查询订单", description = "分页查询订单")
    @PostMapping("/page")
    public ResponseApiData<Page<OrderEntity>> page(@RequestBody QueryOrderPageRequest request) {
        log.info("分页查询订单-开始.请求参数:{}", JSON.toJSONString(request));
        try {
            return ResponseApiData.success(orderService.page(request));
        } catch (Exception e) {
            log.error(String.format("分页查询订单-失败.请求参数:%s", JSON.toJSONString(request)), e);
            return ResponseApiData.systemFail("查询失败");
        }
    }
}
